package main

import (
	"common"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"time"
)

type Input struct {
	Version string
	Url     string
}

func getRemoteVersion() (string, string, error) {
	var input Input
	//resp, err := http.Get("http://101.37.33.124:8090/version")
	//resp, err := http.Get("http://127.0.0.1:8090/version")
	//url := "http://127.0.0.1:8090/version"
	url := "http://101.37.33.124:8090/version"

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", "", err
	}
	var name = "enode_" + runtime.GOARCH
	q := req.URL.Query()
	q.Add("name", name)
	req.URL.RawQuery = q.Encode()
	fmt.Println("req", req.URL.RawQuery)
	resp, err := http.DefaultClient.Do(req)
	if err == nil {
		data, _ := ioutil.ReadAll(resp.Body)
		err = json.Unmarshal(data, &input)
		fmt.Println(input.Version)
		fmt.Println(input.Url)
		version := strings.TrimSpace(input.Version)
		if len(version) == 0 || len(input.Url) == 0 {
			return "", "", errors.New("version empty")
		}
		return version, input.Url, nil
	}
	return "", "", err
}
func getLocalVersion() string {
	return common.GetENodeVersionFromFile("/opt/enode/enode")
}
func Downloadfile(fullURLFile string, fullSaveFile string) error {

	// Create blank file
	file, err := os.Create(fullSaveFile)
	if err != nil {
		return err
	}
	client := http.Client{
		CheckRedirect: func(r *http.Request, via []*http.Request) error {
			r.URL.Opaque = r.URL.Path
			return nil
		},
	}
	// Put content on file
	resp, err := client.Get(fullURLFile)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	size, err := io.Copy(file, resp.Body)
	defer file.Close()
	if size == 0 {
		return errors.New("size 0")
	}
	return err
}
func exeCmd(s string, async bool) error {
	//parts := strings.Split(command, " ")
	cmd := exec.Command("/bin/bash", "-c", s)
	if async {
		cmd.Start()
		return nil
	} else {
		_, err := cmd.Output()
		return err
	}
	//fmt.Println(string(data))

}

func replaceENode(fullSaveFile string) error {
	if err := exeCmd(fmt.Sprintf("chmod +x %s", fullSaveFile), false); err != nil {
		fmt.Println("给权限失败")
		return err
	}

	if err := exeCmd("pkill -9  enode", false); err != nil {
		fmt.Println("关闭enode失败")
		//return err
	}
	if err := exeCmd(fmt.Sprintf("mkdir -p /opt/enode && mv %s /opt/enode/enode", fullSaveFile), false); err != nil {
		fmt.Println("更换文件失败")
		return err
	}
	fmt.Println("启动enode")
	if err := exeCmd("/opt/enode/enode run > /opt/enode/1.log 2>&1", true); err != nil {
		fmt.Println("启动enode失败")
		return err
	}

	fmt.Println("更换enode成功")
	return nil

}
func main() {
	var i uint64 = 0
	for {
		if i > 0 {
			time.Sleep(time.Second * 60)
		}
		i++
		fmt.Println("getRemoteVersion")

		remoteVersion, downloadUrl, err := getRemoteVersion()
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Println("getRemoteVersion ok", remoteVersion, downloadUrl)
		if localVerson := getLocalVersion(); localVerson != remoteVersion {
			//download
			fmt.Println("Downloadfile")
			fullSaveFile := "/tmp/enode"
			if Downloadfile(downloadUrl, fullSaveFile) != nil {
				continue
			}
			fmt.Println("replaceENode")
			err := replaceENode(fullSaveFile)
			fmt.Println(err)
		} else {
			fmt.Println("version same")
		}
	}
}
